package edu.csust.cg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.csust.cg.entity.Book;
import edu.csust.cg.entity.Result;
import edu.csust.cg.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cg
 * @since 2022-05-09
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private IBookService bookService;

    @GetMapping("/getAll")
    public Result getAllStudent() {
        return Result.ok(bookService.list());
    }

    @GetMapping("/getBooksByPage")
    public Result getBooksByPage(@RequestParam Integer current, @RequestParam Integer size, Book book) {
        Page<Book> page = new Page<>(current, size);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (Objects.nonNull(book.getBookId())) {
            wrapper.eq("bookId", book.getBookId());
        }
        if (Objects.nonNull(book.getBookName())) {
            wrapper.like("bookName", book.getBookName());
        }
        if (Objects.nonNull(book.getBookPrice())) {
            wrapper.eq("bookPrice", book.getBookPrice());
        }
        page = bookService.page(page, wrapper);
        return Result.ok(page);
    }

    @PostMapping("/addBook")
    public Result addBook(@RequestBody Book book) {
        if (bookService.save(book)) {
            return Result.ok();
        } else {
            return Result.build(500, "插入失败");
        }
    }

    @GetMapping("/searchBook")
    public Result searchBook(@RequestParam String bookName) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("bookName", bookName);
        return Result.ok(bookService.list(queryWrapper));
    }

    @GetMapping("/deleteBookById")
    public Result deleteBookById(@RequestParam Integer bookId) {
        if (bookService.removeById(bookId)) {
            return Result.ok();
        } else {
            return Result.build(500, "删除失败");
        }
    }

    @PostMapping("/modifyBook")
    public Result modifyBook(@RequestBody Book book) {
        if (bookService.updateById(book)) {
            return Result.ok();
        } else {
            return Result.build(500, "修改失败");
        }
    }

}

